﻿/*
 * dispatcher.cpp
 *
 *  Created on: 2017年6月18日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_PROTOCOL DM_API_EXPORT

#include <dm/os/protocol/dispatcher.hpp>
#include <dm/os/log/logger.hpp>

#include <dm/os/io/monitor.hpp>

namespace dm{
namespace os{
namespace protocol{

static const char* logModule = "CDispatcher.protocol.os.dm";

/**
 * 构造函数。
 * 默认io检测时长500ms
 */
CDispatcher::CDispatcher():m_ioCheckTime(500){
	log().debug(THISMODULE "创建对象");
}

CDispatcher::~CDispatcher(){
	log().debug(THISMODULE "销毁对象");
	free();
}

/**
 * 增加执行器
 * @param executor
 */
void CDispatcher::addExecutor( CExecutor* executor ){
	m_executors.push_back(executor);
}

/**
 * 调度入口函数
 * 周期执行本函数进行调度
 */
void CDispatcher::runOnce(){
	dm::os::io::CMonitor monitor;
	monitor.setSize( m_executors.size());

	// tx操作
	for( unsigned int i=0;i<m_executors.size();++i ){
		CExecutor* ec = m_executors.at(i);
		if( ec->isConnected() ){
			ec->tx();
			monitor.addIo( *(ec->getIo()));
		}else
			ec->tryConnect();
	}

	monitor.wait(m_ioCheckTime);

	// rx
	if(monitor.getCount()>0 ){
		for( unsigned int i=0;i<m_executors.size();++i ){
			CExecutor* ec = m_executors.at(i);
			if( ec->isConnected() && monitor.isIoReady(*ec->getIo()) )
				ec->rx();
		}
	}
}

void CDispatcher::free(){
	for( executors_t::iterator it=m_executors.begin();it!=m_executors.end();++it )
		delete *it;
	m_executors.clear();
}

}
}
}


